<template>
  <a-spin :spinning="confirmLoading" style="background: #fff; padding: 20px">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <div class="subtitle">基本信息</div>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="主体名称">
              <a-input
                :maxLength='15'
                v-decorator="['principalName', { rules: [{ required: true, message: '请输入主体名称' }] }]"
                placeholder="请输入主体名称"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="成立日期">
              <j-date
                placeholder="请选择成立日期"
                v-decorator="['establishTime', { rules: [{ required: true, message: '请选择成立日期' }] }]"
                :trigger-change="true"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="主体代码">
              <a-input v-decorator="['bodyCode',{ rules: [{ required: true, message: '请输入主体代码' }] }]" placeholder="请输入主体代码"   :maxLength='20' style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="法人代表">
              <a-input v-decorator="['legalRepresentative',{ rules: [{ required: true, message: '请输入法人代表' }] }]" :maxLength='5' placeholder="请输入法人代表" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="联系电话">
              <a-input
                :maxLength='11'
                v-decorator="['contactNumber', { rules: [{ required: true, pattern: /^1\d{10}$/, message: '联系电话格式不正确' }] }]"
                placeholder="请输入联系电话"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="员工人数">
               <a-input-number
                :min="0"
                :max="99999"
                v-decorator="['numberOfEmployees',{ rules: [{pattern: /^([1-9]\d*|[0]{1,1})$/, message: '员工人数格式不正确' }] }]"
                placeholder="请输入员工人数"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="经营地址">
              <a-input v-decorator="['businessAddress',{ rules: [{ required: true, message: '请输入经营地址' }] }]" placeholder="请输入经营地址" :style="{'width':disabled?'100%':'90%'}"></a-input>
              <svg t="1639313532242" v-if="!disabled" @click="loadtion" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3731" width="20" height="20"><path d="M210.307143 724.056458a422.3956 422.3956 0 0 1 0-599.801752c166.611598-165.672941 436.774117-165.672941 603.385714 0a422.3956 422.3956 0 0 1 0 599.844418L512 1024l-301.692857-299.943542zM512 554.671556a127.998667 127.998667 0 1 0 0-255.997334 127.998667 127.998667 0 0 0 0 255.997334z" fill="#3D3D3D" p-id="3732"></path></svg>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="经营范围">
              <a-input v-decorator="['natureOfBusiness',{ rules: [{ required: true, message: '请输入经营范围' }] }]" :maxLength='3000' placeholder="请输入经营范围"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24"
          ><a-col :span="24">
            <a-form-model-item label="营业执照" class="license-uploader">
              <j-image-upload
                class="avatar-uploader"
                text="点击上传"
                v-decorator="['businessLicense', { rules: [{ required: true, message: '请上传营业执照' }] }]"
                imgStyle="width: 280px; height: 148.5px;"
              ></j-image-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
        <div class="subtitle t10">详细信息</div>
        <div style="display: flex;jusc">
          <div style="width: calc(100%)">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item label="主体介绍">
                  <a-input
                   :maxLength='3000'
                    v-decorator="['mainBodyIntroduction', { rules: [{ required: true, message: '请输入主体介绍' }] }]"
                    placeholder="请输入主体介绍"
                  ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="联系人">
                  <a-input
                    v-decorator="['contacts', { rules: [{ required: true, message: '请输入联系人' }] }]"
                    :maxLength='5'
                    placeholder="请输入联系人"
                  ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="联系方式">
                  <a-input
                    v-decorator="['contactInformation', { rules: [{ required: true, pattern: /^1\d{10}$/, message: '联系方式格式不正确' }] }]"
                    placeholder="请输入联系方式"
                  ></a-input>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="24"
              ><a-col :span="24">
                <a-form-model-item label="主体图片" class="license-uploader">
                  <j-image-upload
                    class="avatar-uploader"
                    text="点击上传"
                    v-decorator="['mainPicture', { rules: [{ required: true, message: '请上传主体图片' }] }]"
                    imgStyle="width: 280px; height: 148.5px;"
                  ></j-image-upload>
                </a-form-model-item>
              </a-col>
            </a-row>
          </div>
        </div>

        <div class="subtitle t10">荣誉资质</div>
         <a-table :columns="columns" :data-source="sumdata" bordered :pagination='false'>
          <a slot="documentType" slot-scope="text, record,index">
                <a-input v-model="sumdata[index].documentType" :maxLength='15'  placeholder="请输入证件名称"></a-input>
          </a>
          <a slot="certificateNo" slot-scope="text, record,index">
             <a-input v-model="sumdata[index].certificateNo" :maxLength='15' placeholder="请输入证件编号"></a-input>
          </a>
          <a slot="certificatePicture" slot-scope="text, record,index">
          <a-form-model-item label="" class="license-uploader">
              <j-image-upload-custom  
              :disabled="formDisabled"
               listType="text"
               :maxLength="1"
                v-decorator="[`certificatePicture${index}`]"
                text=""
                :isMultiple="false"
                ></j-image-upload-custom>
              {{form.certificatePicture}}
            </a-form-model-item>
              <!-- {{`certificatePicture${index}`}} -->
          </a>
          <a slot="action" slot-scope="text, record,index">
            <span @click="deleteRow(text,record,index)">删除</span>
          </a>
        </a-table>
         <a-button block @click="addsubtitle" v-if="sumdata.length<20">
          新增
        </a-button>
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </j-form-container>
    <a-row style="margin-top:20px">
      <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
        <a-button  v-if="!disabled" type="primary" @click="submitForm" style="margin-left:20px">提 交</a-button>
        <a-button  v-else type="primary" @click="onEdit">编 辑</a-button>
      </a-col>
    </a-row>
      <a-modal v-model="visible_b" :width="1000"  :maskClosable="false" ok-text="确认" cancel-text="取消" @ok="hideModal">
        <a-select
          show-search
          :value="value"
          placeholder="搜索地址"
          style="width: 230px"
          :default-active-first-option="false"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
           @search="seath"
          @change="handleChange"
        >
          <a-icon slot="suffixIcon" type="search" />
          <a-select-option v-for="d in seathvalueList" :key="d.lonlat">
            {{ d.name }}
          </a-select-option>
        </a-select>
        <div id="divwxMap" style="width:97%;height:500px;"></div>
         <p>地址：{{ address }}</p>
         <p>经纬度：{{ point[0]+' , '+ point[1] }}</p>
    </a-modal>
  </a-spin>
</template>
<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { AMapManager } from "vue-amap";
let amapManager = new AMapManager();
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDate from '@/components/jeecg/JDate'
 import JImageUploadCustom from '@/components/jeecg/JImageUploadCustom'
 import JImageUpload from '@/components/jeecg/JImageUpload'
const columns = [
  {
    title: '请输入证件名称',
    key: 'documentType',
    dataIndex: 'documentType',
    scopedSlots: { customRender: 'documentType' },
  },
  {
    title: '证件编号',
    dataIndex: 'certificateNo',
    key: 'certificateNo',
    scopedSlots: { customRender: 'certificateNo' },
  },
  {
    title: '证件图片',
    key: 'certificatePicture',
    dataIndex: 'certificatePicture',
    scopedSlots: { customRender: 'certificatePicture' },
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  },
];
export default {
  name: 'OrCooperativeForm',
  components: {
    JFormContainer,
    JDate,
    JImageUploadCustom,
    JImageUpload
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false,
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false,
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: true,
      required: false,
    },
  },
  data() {
    return {
      action:window._CONFIG['domianURL'] + '/sys/common/upload',
      headers:{},
      visible_b: false,
      seathvalueList:[],
      seathvalue:'',
      flag: true,
      wxMap:null,
      searchOption: {
        city: "北京",//搜索范围 
        citylimit: true, //限制搜索范围
        currentLng:116.397829,
        currentLat:39.907923,
        //city: "", citylimit: false, // 不限制搜索范围搜索，比如想全国搜索				
      },
      lng: "",
      lat: "",
      address: "",
      marker: "",
      point:[120.188522,30.473461], //打点经纬度坐标
      amapManager,
      zoom: 12,
      center: [121.48, 31.22],	
      events: {
      init: (o) => {
        o.getCity((result) => {
          // this.searchOption.city=result.city       
        });
      },
      moveend: () => {},
      zoomchange: () => {},
      click: (e) => {
        self.lng = e.lnglat.lng;
        self.lat = e.lnglat.lat;
        self.center = [self.lng, self.lat];
        let o = amapManager.getMap();
        if (!self.marker) {
          self.marker = new AMap.Marker({
            position: e.lnglat,
          });
          self.marker.setMap(o);
        }
        self.marker.setPosition(e.lnglat);
        let geocoder = new AMap.Geocoder({});
        geocoder.getAddress(e.lnglat, function (status, result) {
          if (status === "complete" && result.regeocode) {
            self.address = result.regeocode.formattedAddress;
          } else {
            console.log("根据经纬度查询地址失败");
          }
        });
      },
      },
      plugin: [
      "ToolBar",
      {
        pName: "MapType",
        defaultType: 0,
        events: {
          init(o) {
          },
        },
      },
      ],
      plugin: [
        {
          pName: "Geolocation",
          events: {
            init(o) {
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  self.lng = result.position.lng;
                  self.lat = result.position.lat;
                  self.address = result.formattedAddress;
                  self.center = [self.lng, self.lat];
                  let o = amapManager.getMap();
                  if (!self.marker) {
                    self.marker = new AMap.Marker({
                      position: self.center,
                    });
                    self.marker.setMap(o);
                  }
                  self.marker.setPosition(self.center);
                }
              });
            },
          },
        },
      ],
      form: this.$form.createForm(this),
      sumdata:[],
      columns,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
          // numberOfEmployees: {rules: [{validator: this.handlePasswordCheck}]},
      },
      url: {
        add: '/loquat/txppSubject/expandUpdate',
        edit: '/loquat/txppSubject/expandUpdate',
        queryById: '/loquat/txppSubject/expandSearch',
      },
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return true
    },
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
    this.handleValue()
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = { 'X-Access-Token': token }
    console.log(this.headers);
  },
  methods: {
    initwxMap() {
      // vue项目需要先声明 T = window.T，不然后面无法获取到。
      let that =this
      if(!this.wxMap){
      var T = window.T;
      this.wxMap = new T.Map('divwxMap'); // div的id
      // 传参中心点经纬度，以及放大程度，最小1，最大18
      }
        // this.wxMap.clearOverLays(); 
        this.wxMap.centerAndZoom(new T.LngLat(that.point[0],that.point[1]), 17);
        this.wxMap.on('click',(e)=>{
        // that.marker.remove()//清除上一次打点实例
        that.point[0] = e.lnglat.lng
        that.point[1] = e.lnglat.lat 
        that.addPoint(that.point)  
        })
    },
    addPoint(e) {
      this.reverseGeocodFun(e)
      },
      // 逆地理坐标查询
    reverseGeocodFun(data){
      this.$axios({
        method: 'get',
        url: `https://api.tianditu.gov.cn/geocoder?postStr={'lon':${data[0]},'lat':${data[1]},'ver':1}&type=geocode&tk=c494b08abe12337f37b9e707363fed10`,
        }).then((res) => {
          if (res.status === 200) {
            this.address= res.data.result.formatted_address
            this.point[0]= res.data.result.location.lon
            this.point[1]= res.data.result.location.lat
            this.wxMap.clearOverLays();
            //创建标注对象
            var marker = new T.Marker(new T.LngLat(res.data.result.location.lon, res.data.result.location.lat));
            //向地图上添加标注
            this.wxMap.addOverLay(marker);
          } else {
            console.log(res.statusText);
          }
        })
      },
    handleChange(e){
        console.log(e);
        let gh =  e.split(',')
        this.wxMap.centerAndZoom(new T.LngLat(gh[0],gh[1]), 17);
        this.wxMap.clearOverLays();
        //创建标注对象
        var marker = new T.Marker(new T.LngLat(gh[0], gh[1]));
        //向地图上添加标注
        this.wxMap.addOverLay(marker);
      },
    seath(val){
      this.$axios({
        method: 'get',
        url: `https://api.tianditu.gov.cn/search?postStr={"keyWord":'${val}',"level":"11","mapBound":"116.04577,39.70307,116.77361,40.09583","queryType":"1","count":"20","start":"0"}&type=query&tk=c494b08abe12337f37b9e707363fed10`,
        }).then((res) => {
          if(res.status==200 && res.data.area){
            this.seathvalueList=[res.data.area]
          }else if(res.status==200 && res.data.pois){
            res.data.pois.forEach(i=>{
                i.lonlat=i.lonlat.split(' ').join(",")
              })
            this.seathvalueList=res.data.pois
          }
        })
      },
    loadtion(){
      this.visible_b=true
      setTimeout(() => {
        this.initwxMap();
      }, 1000);
    },
      hideModal(){
        this.visible_b=false
        this.seathvalue=''
        this.$nextTick(()=>{
          this.form.setFieldsValue({
            businessAddress: this.address,
            longitude:this.point[0],
            latitude:this.point[1]
          })
        });
    },
    deleteRow(text, record,indexs){
      this.form.validateFields((err, values) => {
        console.log(this.sumdata,values);
          this.sumdata.map((i,index)=>{
              i.certificatePicture=values[`certificatePicture${index}`]?values[`certificatePicture${index}`]:''
          })
         this.sumdata= this.sumdata.filter((item,j)=>{
         return indexs!=j
         })
          console.log(this.sumdata,values);
      let EchoFeld =[]
       let po ={}
      this.sumdata.forEach((i,j)=>{
         po[`certificatePicture${j}`] = i.certificatePicture
         EchoFeld.push(`certificatePicture${j}`)
      })
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
           po,
           ...EchoFeld
          )
        )
      })
      })
    },
    editRow(row){
     
    },
    addsubtitle(){
       this.sumdata.push({
              certificateNo:"",
              certificatePicture:"",
              documentType:"",
              key:this.sumdata.length+1
       })
    },
    handleValue() {
      getAction('/loquat/txppSubject/expandSearch', {
      })
        .then(({ code, message, result }) => {
          console.log(result)
          this.sumdata=result.qualifications
          this.sumdata.forEach((i,index)=>{
            i.key=index+1
          })
          this.edit(result)
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
       let EchoFeld =[ 'principalName',
            'establishTime',
            'bodyCode',
            'legalRepresentative',
            'contactNumber',
            'numberOfEmployees',
            'businessAddress',
            'natureOfBusiness',
            'businessLicense',
            'longitude',
            'latitude',
            'mainBodyIntroduction',
            'contacts',
            'contactInformation',
            'mainPicture',
            'documentType',
            'certificateNo',
            'createBy',
            'createTime',
            'updateBy',
            'updateTime',
            'isDelete',
            'sysOrgCode',
            'tenantId',
            'certificatePicture']
      record.qualifications.forEach((i,j)=>{
         this.model[`certificatePicture${j}`] = i.certificatePicture
         EchoFeld.push(`certificatePicture${j}`)
      })
      console.log(this.model);
      this.visible = true
      this.$nextTick(() => {
        setTimeout(() => {
          this.form.setFieldsValue(
            pick(
              this.model,
            ...EchoFeld
            )
          )
        });
      })
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    //编辑
    onEdit() {
      this.disabled = false
    },
    //提交
    submitForm() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'post'
          }
          let formData = Object.assign(this.model, values)
          // formData.qualifications = [
          //   {
          //     certificateNo:formData.certificateNo,
          //     certificatePicture:formData.certificatePicture,
          //     documentType:formData.documentType,
          //   }
          // ]
          formData.qualifications=this.sumdata
          formData.qualifications.map((i,index)=>{
              i.certificatePicture=formData[`certificatePicture${index}`]?formData[`certificatePicture${index}`]:''
          })
        
         let tb = []
         formData.qualifications.forEach((jen,index)=>{
           if(jen.certificateNo==""&& jen.certificatePicture==""&&jen.documentType==""){
               this.sumdata.splice(index,1)
             }else{
                 tb.push(jen)
             }
          })
          formData.qualifications=tb 
          console.log('表单提交数据333', formData)
          httpAction(httpurl, formData, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                this.disabled = true
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }else{
          console.log(values);
          
      }
      }
      )
    },
    popupCallback(row) {
      this.$nextTick(()=>{
        this.form.setFieldsValue(
        pick(
          row,
          'principalName',
          'establishTime',
          'bodyCode',
          'legalRepresentative',
          'contactNumber',
          'numberOfEmployees',
          'businessAddress',
          'natureOfBusiness',
          'businessLicense',
          'longitude',
          'latitude',
          'mainBodyIntroduction',
          'contacts',
          'contactInformation',
          'mainPicture',
          'certificatePicture',
          'documentType',
          'certificateNo',
          'createBy',
          'createTime',
          'updateBy',
          'updateTime',
          'isDelete',
          'sysOrgCode',
          'tenantId'
        )
      )
      })
    },
  },
}
</script>
<style lang="less" scoped>
.license-uploader {
  /deep/ .avatar-uploader > .ant-upload {
    width: 280px;
    height: 148.5px;
  }
}
.head-uploader {
  /deep/ .avatar-uploader > .ant-upload {
    width: 160px;
    height: 200px;
    margin-left: 20px;
  }
}
/deep/ .ant-form-item-label {
  line-height: 30px;
}
.subtitle {
  color: #000;
  font-weight: 500;
  margin-bottom: 10px;
  font-size: 15px;
  &.t10 {
    margin-top: 10px;
  }
}
</style>
